#include "head.h"
#include "login.h"
int exitPipeFd[2];
// 主人通过信号控制工人全部退出
void handler(int num){
    write(exitPipeFd[1],"1",1);
}
/* Usage:  */
int main(){
    pipe(exitPipeFd);
    if(fork()){
        printf("pid=%d\n",getpid());
        close(exitPipeFd[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("All workers exit!\n");
        exit(0);
    }

    configUsrInfo_t *pConfigUsrInfo=(configUsrInfo_t *)calloc(1,sizeof(configUsrInfo_t));  
    getParaMeter(pConfigUsrInfo);
    threadPool_t threadPool;
    threadPool_t *pThreadPool=&threadPool;
    initThreadPool(pThreadPool,atoi(pConfigUsrInfo->workerNum));
    /* initThreadPool(pThreadPool,4); */

    makeWorker(pThreadPool);

    int sockFd=initTcp(pConfigUsrInfo->addr,pConfigUsrInfo->port);
    /* int sockFd=initTcp(argv1,argv2); */
    int epollFd=epoll_create(10);
    epollAdd(epollFd,exitPipeFd[0]);
    epollAdd(epollFd,sockFd);
    int curIdx=0;
    while(1){
        struct epoll_event readySet[1024];
        /* printf("pid=====%d\n",getpid()); */
        int readyNum=epoll_wait(epollFd,readySet,1024,-1);
        for(int i=0;i<readyNum;++i){
            if(readySet[i].data.fd==sockFd){
                //新客户端连接，将netfd加入监听
                int netFd=accept(sockFd,NULL,NULL);
                // 初始化用户信息，包括虚拟文件夹和netFd
                // 登录验证
                pThreadPool->usrInfo[curIdx].netFd=netFd;
                /* pThreadPool->usrInfo[curIdx].curLocation=; */
                /* pThreadPool->usrInfo[curIdx].usrName=; */
                int cnt=0;
                while(cnt<3&&login(&pThreadPool->usrInfo[curIdx])){
                    // 密码错误继续
                    cnt++;
                }
                if(cnt==3){
                    printf("断开连接\n");
                }
                pthread_mutex_lock(&pThreadPool->mutex);
                enQueue(&pThreadPool->taskQueue,pThreadPool->usrInfo[curIdx]);
                pthread_cond_broadcast(&pThreadPool->cond);
                pthread_mutex_unlock(&pThreadPool->mutex);
                ++curIdx;
            }
            else if(readySet[i].data.fd==exitPipeFd[0]){
                // 监听到退出信号
                printf("exit\n");
                pthread_mutex_lock(&pThreadPool->mutex);
                pThreadPool->exitFlag=1;
                pthread_cond_broadcast(&pThreadPool->cond);
                pthread_mutex_unlock(&pThreadPool->mutex);
                for(int j=0;j<pThreadPool->tidArr.workerNum;++j){
                    pthread_join(pThreadPool->tidArr.pWorker[j],NULL);
                }
                printf("all exit\n");
                exit(0);
            }
        }
    }
    return 0;
}
